const { create } = require("xmlbuilder2");
const Assertions = require("./Assertions");
const ConfigElement = require("./ConfigElement");
const Custom = require("./Custom");
const Listener = require("./Listener");
const LogicController = require("./LogicController");
const PostProcessor = require("./PostProcessor");
const PreProcessor = require("./PreProcessor");
const Sampler = require("./Sampler");
const Threads = require("./Threads");

class Jmeter {

    /**
     * 构造函数，用于初始化 Jmeter 类的实例。
     * @param {string} testPlanName - 测试计划的名称，将用于创建测试计划节点。
     */
    constructor(testPlanName = "Test Plan") {
        this.root = this._createRoot();
        this.testPlan = this._createTestPlan(this.root, { testname: testPlanName });
        this.assertions = new Assertions();
        this.configElement = new ConfigElement();
        this.custom = new Custom();
        this.listener = new Listener();
        this.logicController = new LogicController();
        this.postProcessor = new PostProcessor();
        this.preProcessor = new PreProcessor();
        this.sampler = new Sampler();
        this.threads = new Threads();
    }

    _createRoot() {
        const jmxRoot = create({ version: "1.0", encoding: "UTF-8" })
            .ele("jmeterTestPlan", { version: "1.2", properties: "5.0", jmeter: "5.6.3" })
            .ele("hashTree");
        return jmxRoot;
    }

    _createTestPlan(parent, config = { testname: "Test Plan" }) {
        const { testname } = config;
        let jmxTestPlan = parent.ele("TestPlan", { guiclass: "TestPlanGui", testclass: "TestPlan", testname: testname });
        jmxTestPlan.ele("elementProp", { name: "TestPlan.user_defined_variables", elementType: "Arguments", guiclass: "ArgumentsPanel", testclass: "Arguments", testname: "User Defined Variables" })
            .ele("collectionProp", { name: "Arguments.arguments" }).up().up()
            .ele("boolProp", { name: "TestPlan.functional_mode" }).txt("false").up()
            .ele("boolProp", { name: "TestPlan.serialize_threadgroups" }).txt("false")
        const jmxTestPlanHashTree = jmxTestPlan.up().ele("hashTree");
        return jmxTestPlanHashTree;
    }

    toString() {
        return this.root.end({ prettyPrint: true });
    }

}

module.exports = Jmeter;